	<?php
	ob_end_clean();
	ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<meta http-equiv="Content-Script-Type" content="text/javascript" />
		<meta http-equiv="Content-Style-Type" content="text/css" />
	</head>
<body>
<?php
	require_once( '../system/smarty.inc' );
	require_once( '../system/mdao/Class_M_MAP_GROUP.php' );
	require_once( '../system/mdao/Class_M_MAP_GROUP_SHOP.php' );
	require_once( '../system/mdao/Class_M_MAP_GROUP_WEEK.php' );
	
	require_once( '../system/mdao/Class_M_OTHER.php' );
	require_once( '../system/Class_FILE_CSV.php' );
	require_once( '../system/Class_ERROR.php' );
	require_once( '../system/login.inc.php' );
	require_once( '../system/aoki_m.php' );
	require_once( '../system/Class_PWD.php' );
	
	Class_PWD::valid_auth(AOKI_AUTH_MAP_GROUP,$login['staff_auth']);
	
	$isG5 = FALSE ;
	if   ($login['staff_auth'] == 'G-5') {
		$isG5 = TRUE ;
	}
$isG7  = FALSE;
if   ($login['staff_auth'] == 'G-7') {
	$isG7 = TRUE;
}
$smarty->assign('isG7', $isG7 );
	$docsv_import = FALSE;
	$matrix_cd = $_POST["week_cd"];
	//echo $matrix_cd."******";
	
	$csvf = Class_FILE_CSV::get_upload_file();
	
	if ($csvf) {
		// ロケール情報の変更
		$locale = setlocale(LC_ALL, 0);
		setlocale(LC_ALL,'ja_JP.UTF-8');
		$rowall = Class_FILE_CSV::fget_rows($csvf);
		
		if  (!empty($rowall)) {
			//---------------開始------------
			$col_heads = array(
				'matrix_cd'     , //マトリックスID',  1),
				''              , //年度',            1),
				''              , //週',              1),
				''              , //折込日',          1),
				'map_no'        , //マップNO',        1),
				'sort'           , //区分',            1),
				''               , //区分名',          1),
				'media_cd'     , //パターンコード',          1),
				''     ,		 //新聞紙名',          1),
				'shop_cd'        , //店舗コード/サービスコード',    1),
				''               , //店舗名/サービス名', 1),
				'seq'            , //順番',              1),
				'congruent_map'  , //合同マップ',   1),
				'congruent_ins'  , //合同折込',     1),
				'group_no'       , //マップグループNO',1),
				'mark'           , //グループNO　親フラグ',            1),
				'ins_load_ratio' , //折込負担比率', 1),
				'dummy'          , //ダミー',       1),
				'service'        , //サービス',     1),
				'comm'           , //コメント',     1),
				'memo'           , //備考',         1),
				''               , //更新日時',     3),
				''               , //登録日時',     3),
				''               , //更新者',       1)
			);
				

				
			$csvheads  = array();
			$col_index = array();
			foreach ($col_heads as $k => $v) {
				if (!empty($v)) {
					$csvheads[$k]  = $v;
					$col_index[$v] = $k;
				}
			} 

			$index_map_no         = $col_index['map_no'];      //
			$col_map_no           = $index_map_no + 1;
			
			$index_mark           = $col_index['mark'];      //
			$col_mark             = $index_mark + 1;

			$index_congruent_map  = $col_index['congruent_map'];  //合同マップ
			$col_congruent_map    = $index_congruent_map + 1;
			
			$index_congruent_ins  = $col_index['congruent_ins'];  //合同折込
			$col_congruent_ins    = $index_congruent_ins + 1;
			
			$index_group_no       = $col_index['group_no'];      //マップグループNO
			$col_group_no         = $index_group_no + 1;
			
			$index_ins_load_ratio = $col_index['ins_load_ratio'];      //折込負担比率
			$col_ins_load_ratio   = $index_ins_load_ratio + 1;
			
			$index_sort           = $col_index['sort'];      //
			$col_sort             = $index_sort + 1;
			
			$index_shop_cd        = $col_index['shop_cd'];      //
			$col_shop_cd          = $index_shop_cd + 1;
			
			$index_media     = $col_index['media_cd'];      //
			$col_media_name       = $index_media + 1;
			
			$key1 = $index_map_no;    //キーです、必ず仕様します
			$key2 = $index_shop_cd ;  //キーです、必ず仕様します
			
			$err  = new Class_ERROR("","");
			$dao  = new Class_M_MAP_GROUP;
			$daoWeek  = new Class_M_MAP_GROUP_WEEK;
			$daoS = new Class_M_MAP_GROUP_SHOP($dao->get_db());
			
			$ngline  = 0;
			$error_times = 0;
			$error_stop = IMPORT_STOP_MAX_ERROR_TIMES;
			$errtext = array();
			$isng = FALSE;
			//$chk = $dao->get_checks();
			$chk = $daoS->get_checks();
			//$area_arr     = Class_M_OTHER::get_area_array();
			//$media_arr      = Class_M_OTHER::get_media_array();
			$media_arr     = Class_M_OTHER::get_pattern_array(PLEASE_SELECT_ARR, 23);
			
			$shop_arr       = Class_M_OTHER::get_shop_array();
			$service_arr    = Class_M_OTHER::get_service_array();
			$mapvalues      = array();
			$cont_ins_arr   = array();
			foreach ($rowall as $line => $row) {
				$isng = FALSE;
				//CSV内部重複不可チェック
				foreach ($rowall as $kk=>$vv) {
					if  ($line != $kk) {
						if ($row[$key1] == $vv[$key1] && $row[$key2] == $vv[$key2] ){	
							$col = $key1 + 1;
							$col2 = $key2 + 1;
							$isng = TRUE;
							$ngMsg_tmp[$line][] =  "{$line}行と{$kk}行の({$col},{$col2})列目の値重複不可。" ;
							$error_times++;
							if ($error_times > $error_stop) {
								break;
							}
						}
					}
				} 
				
				foreach ( $csvheads as $k=>$v ) {
					$msg =  $err->check( $rowall[$line][$k], $chk[$v ] ); 
					if (!empty($msg)) {
						$isng = TRUE;
						$col  = $k+1;
						$ngMsg_tmp[$line][] = "{$line}行{$col}列目：{$msg}。";
						$error_times++;					
						if ($error_times > $error_stop) {
							break;
						}
					}
				}
				
				if ( !isset( $mapvalues[$row[$index_map_no]] ) ) {
					$where = sprintf(" map_no = '%s'", $row[$index_map_no] );
					//マップＮＯチェック
					if ( !$dao->exits( $where ) ) {
						
						if ( $row[$index_sort] == '3' ) {
							//媒体
							if ( !empty($row[$index_media])){
								if (! $media_arr[$row[$index_media]] ) {
									$isng = TRUE;
									$error_times++;
									$ngMsg_tmp[$line][] = "{$line}行{$col_media_name}列目：パターンは存在しません。";
								}
							} else {
									$isng = TRUE;
									$error_times++;
									$ngMsg_tmp[$line][] = "{$line}行{$col_media_name}列目：区分は3の場合パターンは入力必須です。";
							}
						}
						
						//区分
						if ( isset($row[$index_sort]) && empty($aoki_map_sort[$row[$index_sort]]) ) {
							$isng = TRUE;
							$error_times++;
							$ngMsg_tmp[$line][] = "{$line}行{$col_sort}列目：区分は存在しません。</br>";
						}
						
						$mapvalues[$row[$index_map_no]] = array( "map_no" => $row[$index_map_no],
														"sort"       => $row[$index_sort],
														"media_cd"   => empty($media_arr[$row[$index_media]]) ? 0 : $row[$index_media] ,
														"media_name" => $media_arr[$row[$index_media]] );
					}
					
					
					$where = sprintf(" map_no = '%s'  and matrix_cd = '%s'", $row[$index_map_no],$matrix_cd );
					if ( !$daoWeek->exits( $where ) ) {
						$mapweekvalues[$row[$index_map_no]] = array( "map_no" => $row[$index_map_no],"matrix_cd"       => $matrix_cd);
						
					}
				}
				//店舗
				if ( !empty($row[$index_shop_cd])){
					if ( ! ( isset ($shop_arr[$row[$index_shop_cd]] ) ) ) {
						if ( ! ( isset ($service_arr[$row[$index_shop_cd]] ) ) ) {
							$isng        = TRUE;
							$error_times ++;
							$ngMsg_tmp[$line][] = "{$line}行{$col_shop_cd}列目：店舗/サービスは存在しません。";
						}else {
							$rowall[$line][ $col_index['service'] ] = "1"; 
						}
					}
				}
				//合同マップ
				if ( isset($row[$index_congruent_map])&& (!empty($row[$index_congruent_map])) &&   empty($aoki_congruent[$row[$index_congruent_map]]) ) {
					$isng = TRUE;
					$error_times++;
					$ngMsg_tmp[$line][] = "{$line}行{$col_congruent_map}列目：合同マップは存在しません。";
				}
				
				//合同折込
				if ( isset($row[$index_congruent_ins]) && (!empty($row[$index_congruent_ins])) &&  empty($aoki_congruent_ins[$row[$index_congruent_ins]]) ) {
					$isng = TRUE;
					$error_times++;
					$ngMsg_tmp[$line][] = "{$line}行{$col_congruent_ins}列目：合同折込は存在しません。";
				}
				$rowall[$line][$index_mark]           = $row[$index_mark]== '1'   ? '1' : (empty($row[$index_congruent_ins]) ? '0' : '9') ;
				
				if ( !empty($row[$index_congruent_ins]) ) {
					if (empty($row[ $index_group_no] )) {
						$isng = TRUE;
						$error_times++;
						$ngMsg_tmp[$line][] = "{$line}行{$col_group_no}列目：({$col_congruent_ins}列)合同折込を入力される場合, マップグループNO入力必須です";
					}else {
						$group_no = $row[$index_group_no];
						if ( $cont_ins_arr[$group_no]) {
							$is_same_ins = true;
							foreach ($cont_ins_arr[$group_no] as $gk =>$gv) {
								if ($gv["congruent_ins"] != $row[$index_congruent_ins]) {
									$is_same_ins = false;
								}
							}
							if  (!$is_same_ins ) {
								$isng = TRUE;
								$error_times++;
								$ngMsg_tmp[$line][] = "{$line}行{$col_group_no}列目：同じグループNO「{$group_no}」の合同折込の値は違います";
								//$err_mes["group_no"]  = $err->format_msg("同じグループNO「{$group_no}」の合同折込の値は違います" );
							}else{
								$cont_ins_arr[$group_no][$line]["congruent_ins"] =  $row[$index_congruent_ins] ;
								$cont_ins_arr[$group_no][$line]["mark"] =  $row[$index_mark] ;
							}
						}  else {
							$cont_ins_arr[$group_no][$line]["congruent_ins"] =  $row[$index_congruent_ins] ;
							$cont_ins_arr[$group_no][$line]["mark"] =  $row[$index_mark] ;
						}
					}
					if (empty($row[$index_ins_load_ratio])) {
						$isng = TRUE;
						$error_times++;
						$ngMsg_tmp[$line][] = "{$line}行{$col_ins_load_ratio}列目：({$col_congruent_ins}列)合同折込を入力される場合, 折込負担比率入力必須です";
					}
				}
				if (empty($row[$index_ins_load_ratio])) {
					$rowall[$line][$index_ins_load_ratio] = 0;
				}
				
				/*
				//記号
				if ( isset($row[$index_mark]) && empty($aoki_congruent[$row[$index_mark]]) ) {
					$isng = TRUE;
					$error_times++;
					$ngMsg_tmp[$line][] = "{$line}行{$col_mark}列目：記号は存在しません。</br>";
				}
				*/
				//for (i)lnews1
				if ( $isng ) {
					++$ngline;
					//$errtext[$ngline] = $row;
					if ($error_times > $error_stop) {
						break;
					}
				}
			}
			
			if (!$isng) {
				$all_line = $line + 1;
				foreach ( $cont_ins_arr as $kk => $vv ) {
					$count_all = 0;
					$count_parent = 0;
					$group_no = $kk;
					foreach ( $vv as $key => $val ) {
						$congruent_ins = $val["congruent_ins"];
						$count_all ++;
						if ($val["mark"] == '1') {
							$count_parent++;
						}
					}
					if ($count_parent != 1) {
						$isng = TRUE;
						$error_times++;
						$ngMsg_tmp[$all_line][] = "全体：グループNO「{$group_no}」の親店舗はひとつを指定してください" ;
					}
					$count_G = substr(trim($val["congruent_ins"]),0,1) * 1 ;
					if ($count_all != $count_G ) {
						$isng = TRUE;
						$error_times++;
						$ngMsg_tmp[$all_line][]   = "全体：グループNO「{$group_no}」の店舗数({$count_all})と合同折込数({$count_G})は違います" ;
					}
				}
			}
			if ( $isng ) {
				++$ngline;
				//$errtext[$ngline] = $row;
			}
			
			if ($ngline > 0) {
				$errHtml = Class_FILE_CSV::format_msg($ngMsg_tmp);				
				if ($error_times > $error_stop) {
					Class_FILE_CSV::write_msg_error( $errHtml ,$error_stop );	
				
				} else {
					Class_FILE_CSV::write_msg_error( $errHtml );	
				}
			} else {
				//DBへ更新
				try {
					$daodb = $dao->get_db();
					$dao->begin_trans();
					$i = 0;
					$percent = "";
					$percentold = "";
					
					foreach  ( $mapvalues as $gk=>$gv ) {
						if ($gv) {
							$xxx = $dao->add0( $gv);
							
							if ( !( $xxx ) ) {
							
								throw  new Exception("mmapshop_import db更新");
							}
						}
					}
					
					foreach  ( $mapweekvalues as $gk=>$gv ) {
						if ($gv) {
							$xxx = $daoWeek->add( $gv);
							
							if ( !( $xxx ) ) {
							
								throw  new Exception("mmapshop_import db更新");
							}
						}
					}
					foreach ( $rowall as $k=>$v ) {
						$i++;
						$percent = intval($i/$line * 100)."%";
						if  ( $percent != $percentold ) {
							Class_FILE_CSV::write_msg_doing( $percent ) ;
						}
						$percentold = $percent;
	
						$values  = array();
						$values["matrix_cd"] = $matrix_cd ;
						$values["map_no"] = $v[$col_index["map_no"]] ;
						$values["seq"] = empty($v[$col_index["seq"]]) ? '99' : $v[$col_index["seq"]] ;
						$values["shop_cd"] = $v[$col_index["shop_cd"]] ;
						$values["group_no"] = $v[$col_index["group_no"]] ;
						$values["mark"] = $v[$col_index["mark"]] ;
						$values["comm"] = $v[$col_index["comm"]] ;
						$values["congruent_map"] = $v[$col_index["congruent_map"]] ;
						$values["congruent_ins"] = $v[$col_index["congruent_ins"]] ;
						$values["ins_load_ratio"] = $v[$col_index["ins_load_ratio"]] ;
						$values["memo"] = $v[$col_index["memo"]] ;
						$values["dummy"] = $v[$col_index["dummy"]] ;
						$values["service"]  = $v[$col_index["service"]] ;
						//$values["shop_flg"] = 0 ;
						 
						$where = sprintf(" matrix_cd = '%s' and map_no = '%s' and shop_cd = '%s'",$matrix_cd,$values["map_no"],$values["shop_cd"] );
						if ( !$daoS->exits( $where ) ) {
							if ( !( $daoS->add( $values ) ) ) {
								throw  new Exception("mmapshop_import db更新");
							}
						}else {
							
							if ( !( $daoS->editbywhere($where, $values) ) ) {
								throw new Exception("mmapshop_import db更新");
							}
						}
						/*
						foreach ( $csvheads as $kk => $vv ) {
							$values[$vv] = $v[$kk];
						}
						$keyvalues =  $values[$col_heads[$key1]];
						$where     = sprintf(" matrix_cd =  {$matrix_cd} AND {$col_heads[$key1]} = '%s'", $keyvalues );
						$values["matrix_cd"]  =   $matrix_cd;
						$values["hand_cd"]           =  Class_M_OTHER::do_hand($values["hand_name"], $daodb);
						$values["publish_map_no"]   =  Class_M_OTHER::do_publish_area($values["publish_area_name"], $daodb);
						$values["area_name"]         =  $area_arr[$values["map_no"]];
						$values["media_cd"]          =  array_search($values["media_name"], $media_arr) ;
						//$values["stop_date"]         =  Class_PWD::date_to_int8 ( $values['stop_date'] );
						*/
						

					}
					Class_FILE_CSV::write_msg_succed($line, "mmapshop");
					$dao->commit_trans();
					
				} catch (Exception $e) {
					$dao->rollback_trans();
					Class_FILE_CSV::write_msg_error( "DB Exceptionがありました。</br>" );
				}
			} 
				//--------11地域広告inCSV-------完了------------
		}else {

		$errHtml = "CSVファイルエラー";
		Class_FILE_CSV::write_msg_error( $errHtml );
			
		}
		
		// ロケール情報の復元
		setlocale(LC_ALL, $locale);
	
	}else {

		$errHtml = "CSVファイルエラー";
		Class_FILE_CSV::write_msg_error( $errHtml );
	}
?>
</body>
	</himl>
	